﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace Com.CodePlex.SPC3.ListProfileFieldCreator.ListProfileFieldCreator {

    [ToolboxItemAttribute(false)]
    public class ListProfileFieldCreator : WebPart {

        Label txtListTitle;
        HiddenField hiddenListId = new HiddenField();
        TextBox txtFieldName;
        DropDownList ddlSourceField;
        DropDownList ddlTargetField;
        Button saveButton;
        Button cancelButton;

        SPList sourcelist;
        SPList targetlist;

        protected override void CreateChildControls() {
            HtmlTable table = new HtmlTable();
            HtmlTableRow tr = new HtmlTableRow();
            HtmlTableCell td = new HtmlTableCell();
            td.Controls.Add(new LiteralControl("List title:"));
            tr.Cells.Add(td);
            td = new HtmlTableCell();
            txtListTitle = new Label();
            td.Controls.Add(txtListTitle);
            td.Controls.Add(hiddenListId);
            tr.Cells.Add(td);
            table.Rows.Add(tr);
            tr = new HtmlTableRow();
            td = new HtmlTableCell();
            td.Controls.Add(new LiteralControl("Field name:"));
            tr.Cells.Add(td);
            td = new HtmlTableCell();
            txtFieldName = new TextBox();
            txtFieldName.ID = "name";
            td.Controls.Add(txtFieldName);
            tr.Cells.Add(td);
            table.Rows.Add(tr);
            tr = new HtmlTableRow();
            td = new HtmlTableCell();
            td.Controls.Add(new LiteralControl("List field:"));
            tr.Cells.Add(td);
            td = new HtmlTableCell();
            ddlSourceField = new DropDownList();
            ddlSourceField.ID = "source";
            td.Controls.Add(ddlSourceField);
            tr.Cells.Add(td);
            table.Rows.Add(tr);
            tr = new HtmlTableRow();
            td = new HtmlTableCell();
            td.Controls.Add(new LiteralControl("Profile field:"));
            tr.Cells.Add(td);
            td = new HtmlTableCell();
            ddlTargetField = new DropDownList();
            ddlTargetField.ID = "target";
            td.Controls.Add(ddlTargetField);
            tr.Cells.Add(td);
            table.Rows.Add(tr);
            Controls.Add(table);

            Controls.Add(new LiteralControl("<br/>"));

            Panel buttons = new Panel();
            buttons.Style["display"] = "none";
            buttons.Style["visible"] = "hidden";
            saveButton = new Button();
            saveButton.UseSubmitBehavior = false;
            saveButton.ID = "save";
            saveButton.Text = "Ok";
            saveButton.Click += new EventHandler(saveButton_Click);
            buttons.Controls.Add(saveButton);
            cancelButton = new Button();
            cancelButton.UseSubmitBehavior = false;
            cancelButton.ID = "cancel";
            cancelButton.Text = "Cancel";
            buttons.Controls.Add(cancelButton);
            Controls.Add(buttons);
        }

        protected Guid ListGuid {
            get {
                if (!string.IsNullOrEmpty(hiddenListId.Value)) {
                    return new Guid(hiddenListId.Value);
                }
                return new Guid(Page.Request["List"]);
            }
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            sourcelist = SPContext.Current.Web.Lists[ListGuid];
            if (sourcelist == null) {
                return;
            }
            targetlist = SPContext.Current.Web.Lists["User Information List"];
            if (targetlist == null) {
                return;
            }

            if (!Page.IsPostBack) {
                DataBind();
            }
        }

        public override void DataBind() {
            base.DataBind();

            txtListTitle.Text = sourcelist.Title;
            hiddenListId.Value = ListGuid.ToString();
            cancelButton.OnClientClick = "window.location.href='" + CancelUrl + "'; return false;";

            ddlSourceField.Items.Clear();
            ddlSourceField.Items.Add(new ListItem());
            foreach (SPField field in sourcelist.Fields) {
                if (!field.Hidden) {
                    if (field.Type == SPFieldType.User) {
                        ddlSourceField.Items.Add(new ListItem(field.Title, field.InternalName));
                    }
                }
            }

            ddlTargetField.Items.Clear();
            ddlTargetField.Items.Add(new ListItem());
            foreach (SPField field in targetlist.Fields) {
                if (!field.Hidden) {
                    ddlTargetField.Items.Add(new ListItem(field.Title, field.Id.ToString()));
                }
            }
        }

        private void saveButton_Click(object sender, EventArgs e) {
            SPField primaryCol = sourcelist.Fields.GetFieldByInternalName(ddlSourceField.SelectedValue);
            string strSecondaryColName = sourcelist.Fields.AddDependentLookup(txtFieldName.Text, primaryCol.Id);
            SPFieldLookup secondaryCol = (SPFieldLookup)sourcelist.Fields.GetFieldByInternalName(strSecondaryColName);
            secondaryCol.LookupField = targetlist.Fields[new Guid(ddlTargetField.SelectedValue)].InternalName;
            secondaryCol.Update();

            sourcelist.DefaultView.ViewFields.Add(secondaryCol);

            //note: cant use Page.Response.Redirect in sandbox
            Controls.Add(new LiteralControl(@"
<script type='text/javascript'>
window.location.href = '" + CancelUrl + @"'
</script>
"));
        }

        protected string CancelUrl {
            get {
                string url = sourcelist.ParentWebUrl;
                if (!url.EndsWith("/")) {
                    url += "/";
                }
                return url + @"_layouts/listedit.aspx?List=" + SPHttpUtility.UrlKeyValueEncode(sourcelist.ID); 
            }
        }
    }
}


